package com.yeeft.ocr.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yeeft.ocr.domain.entity.OcrLog;
import com.yeeft.ocr.domain.enums.AliCommonEnum;
import com.yeeft.ocr.domain.enums.CertificateTypeEnum;
import com.yeeft.ocr.domain.enums.SupplierEnum;
import com.yeeft.ocr.domain.model.request.OcrRequest;
import com.yeeft.ocr.domain.model.response.OcrResponse;
import com.yeeft.ocr.domain.props.OcrAliProps;
import com.yeeft.ocr.domain.vo.AliOcrData;
import com.yeeft.ocr.domain.vo.CompanyLicense;
import com.yeeft.ocr.mapper.OcrLogMapper;
import com.yeeft.ocr.utils.DateUtils;
import com.yeeft.ocr.utils.HttpUtils;
import com.yeeft.ocr.utils.Sha1KeyGenerator;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 功能简要描述
 *
 * @author 赵仲文
 * @Copyright (c) 2016, frontpay.cn
 * @date 2018/5/9 9:57
 */
@Slf4j
@Data
@Service
public class CompanyLicenseAliService {
    @Autowired
    private OcrAliProps ocrAliProps;
    @Autowired
    private OcrLogMapper ocrLogMapper;

    public OcrResponse<CompanyLicense> getCompanyLicense(OcrRequest request) {
        log.info("处理营业执照识别请求！ data={}", JSONObject.toJSON(request));

        String host = ocrAliProps.getHost();
        String path = ocrAliProps.getPath();
        String method = ocrAliProps.getMethod();
        String appcode = ocrAliProps.getAppCode();
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        AliOcrData aliOcrData = new AliOcrData();
        aliOcrData.setImage(request.getImage());
        OcrResponse<CompanyLicense> data = new OcrResponse<>();
        String jsonBody = null;

        try {

            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, JSONObject.toJSONString(aliOcrData));
            jsonBody = EntityUtils.toString(response.getEntity());

            //jsonBody = "{\"address\":\"海南省三沙市永兴岛宣德路西沙宾馆106-97(海南省文昌市百灵顿华侨星城G2号楼3单元310)\",\"angle\":0,\"business\":\"水产养殖、排捞、加工及销售,旅游观光、蔬菜种植。(一般经营项目自主经营,许可经营项目凭相关许可证或者批准文件经营)(依法须经批准的项目,经相关部门批准后方可开展经营活动。)=\",\"captial\":\"贰仟万元人民币\",\"elbem\":{\"height\":113,\"left\":241,\"top\":53,\"width\":111},\"establish_date\":\"20150921\",\"name\":\"三沙信达水产科技有限公司\",\"person\":\"刘正航\",\"qrcode\":{\"height\":82,\"left\":80,\"top\":641,\"width\":87},\"reg_num\":\"91460600MA5RC30P9Y\",\"request_id\":\"20180521163243_5bb5edc31038b209fed4dd1ac05133b5\",\"stamp\":{\"height\":125,\"left\":388,\"top\":643,\"width\":121},\"success\":true,\"title\":{\"height\":66,\"left\":136,\"top\":176,\"width\":332},\"valid_period\":\"20650921\"}";

            JSONObject object = JSON.parseObject(jsonBody);
            data.setLogId(object.getString("request_id"));
            data.setSuccess(object.getBoolean("success"));
            CompanyLicense companyLicense = new CompanyLicense();
            String regNum = object.getString("reg_num");
            companyLicense.setLicenseNo(regNum.equals(AliCommonEnum.FailedInRecognition.getName()) ? null : regNum);
            String name = object.getString("name");
            companyLicense.setName(name.equals(AliCommonEnum.FailedInRecognition.getName()) ? null : name);
            String person = object.getString("person");
            companyLicense.setOwner(person.equals(AliCommonEnum.FailedInRecognition.getName()) ? null : person);
            String address = object.getString("address");
            companyLicense.setAddress(address.equals(AliCommonEnum.FailedInRecognition.getName()) ? null : address);
            String validDate = object.getString("valid_period");
            companyLicense.setValidDate(validDate.equals(AliCommonEnum.FailedInRecognition.getName()) ? null :
                    DateUtils.formatDate(DateUtils.parseDate(validDate, "yyyyMMdd"), "yyyy-MM-dd"));
            String captial = object.getString("captial");
            companyLicense.setCaptial(captial.equals(AliCommonEnum.FailedInRecognition.getName()) ? null : captial);
            String business = object.getString("business");
            companyLicense.setBusiness(business.equals(AliCommonEnum.FailedInRecognition.getName()) ? null : business);

            data.setData(companyLicense);

        } catch (Exception e) {
            log.error("调用Ali OCR营业执照接口失败！");
            log.error(e.getMessage(), e);
            data.setSuccess(false);
            data.setReason(e.getMessage());
            jsonBody = data.getReason();
        }

        // 记录此次识别到日志表
        OcrLog ocrLog = new OcrLog();
        ocrLog.setAppId(request.getRequestHead().getAppId());
        ocrLog.setBizId(CertificateTypeEnum.YingYeZhiZhao.getCode());
        ocrLog.setImageUrl(request.getImageUrl());
        ocrLog.setLogId(data.getLogId());
        ocrLog.setResult(jsonBody);
        ocrLog.setSupplierId(SupplierEnum.Aliyun.getCode());
        ocrLog.setOcrId(Sha1KeyGenerator.get(ocrLog.getAppId(), ocrLog.getSupplierId(), ocrLog.getImageUrl()));

        ocrLogMapper.insert(ocrLog.getOcrId(), ocrLog.getAppId(), ocrLog.getSupplierId(),
                ocrLog.getBizId(), ocrLog.getLogId(), ocrLog.getImageUrl(), ocrLog.getResult());

        return data;
    }
}
